package cn.SiFuLan.controls;

import cn.SiFuLan.dao.IbrandDao;
import cn.SiFuLan.dao.impl.brandDaoImpl;
import cn.SiFuLan.entity.brandEntity;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet(urlPatterns = "/admin/badd.shtml")
public class baddServlt extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.实例化对象
        SmartUpload smart = new SmartUpload();
        smart.setCharset("utf-8");
//2.初始化上传
        smart.initialize(this.getServletConfig(),request,response);
        try {
            //3.准备上传
            smart.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        String path = request.getSession().getServletContext().getRealPath("/upload");
        File file = smart.getFiles().getFile(0);
        System.out.println(path);

        System.out.println("获取文件名称："+file.getFileName());
        System.out.println("获取文件大小："+file.getSize());
        System.out.println("获取文件类型："+file.getFileExt());
        System.out.println(path);

//获取扩展名
        String ext = file.getFileExt();//png   jpg
//4.保存文件1\\\\\\\\
//mall/upload/2000202020.png
        String fileName = new Date().getTime()+"."+ext;
        try {
            file.saveAs(path+"/"+fileName);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        System.out.println(fileName);

        IbrandDao ibrandDao=new brandDaoImpl();
        brandEntity brand=new brandEntity();
        brand.setImageAddress(fileName);
        brand.setBrand_Name(smart.getRequest().getParameter("title"));
        brand.setInitial(smart.getRequest().getParameter("gg"));
        brand.setBrand_Info(smart.getRequest().getParameter("jg"));
        brand.setAddTime(new Date());
        brand.setUpdateTime(null);

        if(ibrandDao.add(brand)){
            response.sendRedirect("index1.do");
        }else {
            System.out.println("失败");
        }
    }
}
